/*
 * RoboEye - Web client for www.newocr.com that allows you
 * to recognize an image captured by the camera.
 *
 * Copyright (C) Oxygen Development, 2011
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package com.devoxy.roboeye.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import com.devoxy.roboeye.R;
import com.devoxy.roboeye.global.IntentHelper;
import com.devoxy.roboeye.global.exceptions.CannotListFilesException;
import com.devoxy.roboeye.global.log.Log;
import com.devoxy.roboeye.ui.DialogHelper;
import com.devoxy.roboeye.ui.NotificationHelper;
import com.devoxy.roboeye.ui.activity.main.RoboEyeListActivity;
import com.devoxy.roboeye.ui.adapter.FileAdapter;
import com.devoxy.roboeye.ui.component.actionbar.ActionBar;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Oxygen Development.
 * Author: Dmitriy Tarasov (dm.vl.tarasov@gmail.com)
 * Date: 25.06.11
 * Time: 20:43
 */
public class FileBrowserActivity extends RoboEyeListActivity {

    private static final String TAG = FileBrowserActivity.class.getName();
    private static final String SLASH = "/";
    private static final String CURRENT_LOCATION_TAG = "current_location";

    private ActionBar actionBar;

    private File initLocation;
    private File currentLocation;
    private File levelUpLocation;

    private Dialog newFolderDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.file_browser);
        initProperties(savedInstanceState);
        initBehavior(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshList();
    }

    private void refreshList() {
        try {
            initUI(null);
        } catch (CannotListFilesException e) {
            Log.d(TAG, "cannot open folder " + currentLocation, e);
            NotificationHelper.showText(this, R.string.cannot_list_folder);
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        File f = (File) l.getAdapter().getItem(position);
        if (f.isDirectory()) {
            File oldLocation = currentLocation;
            currentLocation = f;
            levelUpLocation = currentLocation.getParentFile();
            try {
                initUI(null);
            } catch (CannotListFilesException e) {
                currentLocation = oldLocation;
                levelUpLocation = currentLocation.getParentFile();
                Log.d(TAG, "cannot open folder " + currentLocation, e);
                NotificationHelper.showText(this, R.string.cannot_list_folder);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            levelUp();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putSerializable(CURRENT_LOCATION_TAG, currentLocation);
    }

    public void okHandler(View view) {
        Intent data = new Intent();
        data.putExtra(IntentHelper.PATH, currentLocation.getAbsolutePath());
        setResult(RESULT_OK, data);
        finish();
    }

    public void cancelHandler(View view) {
        setResult(RESULT_CANCELED);
        finish();
    }

    public void newFolderHandler(View view) {
        newFolderDialog = DialogHelper.showEditTextDialog(this,
                R.string.create_new_folder,
                R.string.enter_folder_name,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                },
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        EditText text = (EditText) newFolderDialog.findViewById(R.id.value);
                        String path = currentLocation.getAbsolutePath() + SLASH + text.getText();
                        File newFolder = new File(path);
                        Context context = FileBrowserActivity.this;
                        if (newFolder.mkdir()) {
                            NotificationHelper.showText(context, R.string.new_folder_created);
                            refreshList();
                        } else {
                            NotificationHelper.showText(context, R.string.cannot_create_folder);
                        }
                        dialog.dismiss();
                    }
                });
        newFolderDialog.show();
    }

    public void levelUpHandler(View view) {
        levelUp();
    }

    @Override
    public void initProperties(Bundle bundle) {
        actionBar = (ActionBar) findViewById(R.id.actionbar);
        String initLocation = getIntent().getStringExtra(IntentHelper.INIT_LOCATION);
        if (bundle != null && bundle.get(CURRENT_LOCATION_TAG) != null) {
            this.initLocation = (File) bundle.get(CURRENT_LOCATION_TAG);
        } else if (!TextUtils.isEmpty(initLocation)) {
            this.initLocation = new File(initLocation);
        } else {
            this.initLocation = Environment.getExternalStorageDirectory();
        }
        currentLocation = this.initLocation;
        levelUpLocation = currentLocation.getParentFile();
    }

    @Override
    public void initUI(Bundle bundle) {
        updateFilesList();
        actionBar.setCaption(currentLocation.getAbsolutePath());
    }

    @Override
    public void initBehavior(Bundle bundle) {
        findViewById(R.id.actionbar_home).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });
    }

    private void updateFilesList() {
        File[] allItems = currentLocation.listFiles();
        if (allItems == null) {
            throw new CannotListFilesException("Cannot list files in " + currentLocation.getAbsolutePath());
        }
        List<File> dirs = new ArrayList<File>();
        List<File> files = new ArrayList<File>();
        for (File f : allItems) {
            if (f.isDirectory()) {
                dirs.add(f);
            } else if (f.isFile()) {
                files.add(f);
            }
        }

        Comparator<File> comparator = new AlphaBeticalComparator();
        Collections.sort(dirs, comparator);
        Collections.sort(files, comparator);
        dirs.addAll(files);

        FileAdapter adapter = new FileAdapter(this,
                R.layout.file_browser_item,
                R.id.item,
                dirs);

        if (levelUpLocation == null) {
            levelUpLocation = new File(SLASH);
        }
        adapter.insert(levelUpLocation, 0);

        setListAdapter(adapter);
    }

    private void levelUp() {
        onListItemClick(getListView(), null, 0, 0);
    }

    private class AlphaBeticalComparator implements Comparator<File> {
        @Override
        public int compare(File object1, File object2) {
            return object1.getName().compareTo(object2.getName());
        }
    }

}
